var experss = require('express');
var router = experss.Router();
var db = require("../public/javascripts/db");

var _ = require("lodash");


router.get('/', function(req, res, next) {
    console.log(req.url)
    let type = _.trim(String(req.query.type));
    let departid = _.trim(String(req.query.departid));
    let workshopid = _.trim(String(req.query.workshopid));


    let data = {
        isSuccess: false,
        data: {},
        msg: '数据获取失败！'
    };
 
    let whereClause ="";
    let tableName = '';
    let sql = '';
    if(departid && !workshopid) {
        whereClause = ' id=' + departid;
    } 
    if(workshopid && !departid ) {
        whereClause = ' id=' + workshopid;
    }
    if(workshopid && departid ) {
        whereClause = ' id=' + departid + ' AND id=' + workshopid;
    }
    switch(type) {
        case 'equipment':
            sql = whereClause ? ('select * from equipmentinfo where ' + whereClause) : ('select * from equipmentinfo');
            break;
        case 'event':
            let tempSql2 = 'Select a.*, b.name assistantname, c.name assistant1name, d.name recorder '
            + 'From event_record a left join sys_user b on a.assistant=b.id '
            + 'left join sys_user c on a.assistant1=c.id left join sys_user d on a.recorderid=d.id';
            sql = whereClause ? (tempSql2 + " WHERE  zcbh='' AND " + whereClause) : tempSql2 + " WHERE  zcbh=''";
            break;
        case 'demand':
            let tempSql3 = "SELECT t2.name AS type, t1.* FROM demand_record AS t1 LEFT JOIN sys_demand_type AS t2  ON t1.typecode = t2.id";
            sql = whereClause ? ( tempSql3 + " where " + whereClause) : tempSql3;
            break;
        default:
            return res.json(data);
            break;
    }
    console.log("sql: " + sql);
    db.execute(sql, function(err, rows) {
        if(err) {
            return res.json(data);
        } else {
            if(rows.length > 0) {
                data.data = rows;
                data.isSuccess = true;
                data.msg = "数据获取成功！";
                console.log(data)
                return res.json(data);
            } else {
                data.msg = "暂无数据！";
                data.isSuccess = true;
                data.data = [];
                return res.json(data);
            }
        }
    })
});

module.exports = router;